package com.member.provider.service.impl;

import cn.hutool.system.UserInfo;
import com.member.dto.PayType;
import com.member.dto.User;
import com.member.provider.mapper.MemberMapper;
import com.member.provider.service.MemberService;
import com.member.utils.Result;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @auther liujian
 * @date 2024/1/5 13:46
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @Description TODO
     * @param
     * @retuen List<UserInfo></>
     * @date 2024/1/5 14:15
     * @auther 银狐先生
     */
    @Override
    public Result getUserInfo() {
        List<UserInfo> userInfos = memberMapper.getUserInfo();
        return Result.success(userInfos);
    }

    @Override
    public Result updatePayType(PayType payType) {
        int pay_id=payType.getPayId();
        int i=memberMapper.updatePayType(pay_id);
        if (i>0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }

    }

    @Override
    public Result login(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        User userDB=memberMapper.selectByName(userName);
        if (userDB==null){
            return Result.error("用户名不存在，请重新输入");
        }
        if (!new BCryptPasswordEncoder().matches(password,userDB.getPassword())){
            return Result.error("密码输入错误，请重新输入");
        }

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, "xft-ymt")
                .claim("uid", userDB.getId())
                .compact();
        //登录成功并生成jwt令牌token
        redisTemplate.opsForValue().set(userDB.getId()+":token",token,15, TimeUnit.MINUTES);

        return Result.success(token);

    }

    @Override
    public Result register(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        if (userName==null||password==null){
            return Result.error("用户名或者密码不能为空");
        }
        User user1 = memberMapper.login(userName, password);
        if (user1!=null){
            return Result.error("用户名已存在,无法注册");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        user.setId(uuid);
        int i=memberMapper.register(user);
        if (i>0){
            return Result.success("注册成功");
        } else{
            return Result.error("注册失败");
        }
    }
}
